package com.ge.med.cchelper.popup.job;

import java.io.File;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;

import com.ge.med.cchelper.bean.Response;
import com.ge.med.cchelper.util.LogUtil;
import com.ge.med.cchelper.util.ReourceHelper;
import com.ge.med.cchelper.util.SSLhelper;
import com.ge.med.cchelper.util.TextHelper;

public class CheckinJob extends BaseJob{

	private IFile selectedIFile;
	private String comments;
	
	public CheckinJob(String message,IFile selectedIFile,String comments) {
		super(message);
		this.selectedIFile = selectedIFile;	
		this.comments = comments;
	}

	
	protected IStatus start(IProgressMonitor arg0) {
			String noUse = selectedIFile.getFullPath().segment(1);
			String allPath = selectedIFile.getFullPath().toString();
			String realTempPath = allPath.substring(allPath
					.indexOf(noUse) + noUse.length());
			String fileName = selectedIFile.getFullPath()
					.lastSegment();

			String fullPath = selectedIFile.getLocation()
					.toOSString();
			String vobsPath = csession.getVobRoot();
			String remotePath = vobsPath + realTempPath;

			LogUtil.out("checkin " + fileName + "...");
			
			try {
				
				SSLhelper sslHelper = new SSLhelper(csession);
				Response res0 = sslHelper.executeCheckin(comments,remotePath);
				if (res0.status == 0) {
					LogUtil.out("Checkin completed.");
				}else{
					LogUtil.out("Checkin fail! please check code.");
					return Status.CANCEL_STATUS;
				}
				
			} catch (Exception e) {
				e.printStackTrace();
				return Status.CANCEL_STATUS;
			}
			
			try {
				IProject currentProject =ReourceHelper.getProject();
				String confdir =  currentProject.getLocation().toOSString();
				TextHelper.remove(confdir+File.separator+TextHelper.CHECKOUT_FILE, allPath);
			} catch (Exception e1) {
				e1.printStackTrace();
				LogUtil.err("remove checkout flag failed."
						+ e1.getMessage());
			}
			return Status.OK_STATUS;
		}

}
